package hero.mps.web.sys_notice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import hero.mps.utils.ResultUtils;
import hero.mps.utils.ResultVo;
import hero.mps.web.sys_notice.entity.NoticeListParam;
import hero.mps.web.sys_notice.entity.SysNotice;
import hero.mps.web.sys_notice.service.SysNoticeService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/sys/notice")
@RequiredArgsConstructor
public class SysNoticeController {
    private final SysNoticeService sysNoticeService;

    /**
     * 查询最新发布的前三个
     * @return
     */
    @GetMapping("/getTopList")
    public ResultVo getTopList() {
        LambdaQueryWrapper<SysNotice> queryWrapper = Wrappers.lambdaQuery(SysNotice.class)
                .orderByDesc(SysNotice::getCreateTime)
                .last("limit 3");
        List<SysNotice> list = sysNoticeService.list(queryWrapper);
        return ResultUtils.success("查询成功", list);
    }
    /**
     * 新增
     * @param sysNotice
     * @return
     */
    @PostMapping
    public ResultVo add(@RequestBody SysNotice sysNotice) {
        sysNotice.setCreateTime(new java.util.Date());
        boolean save = sysNoticeService.save(sysNotice);
        if (save) {
            return ResultUtils.success("新增成功");
        }else {
            return ResultUtils.error("新增失败");
        }
    }

    /**
     * 修改
     * @param sysNotice
     * @return
     */
    @PutMapping
    public ResultVo update(@RequestBody SysNotice sysNotice) {
        sysNotice.setCreateTime(new java.util.Date());
        boolean updateById = sysNoticeService.updateById(sysNotice);
        if (updateById) {
            return ResultUtils.success("修改成功");
        }else {
            return ResultUtils.error("修改失败");
        }
    }

    /**
     * 删除
     * @param noticeId
     * @return
     */
    @DeleteMapping("/{noticeId}")
    public ResultVo delete(@PathVariable Integer noticeId) {
        boolean delete = sysNoticeService.removeById(noticeId);
        if (delete) {
            return ResultUtils.success("删除成功");
        } else {
            return ResultUtils.error("删除失败");
        }
    }

    @GetMapping("/list")
    public ResultVo list(NoticeListParam param) {
        IPage<SysNotice> page = new Page<>(param.getCurrentPage(), param.getPageSize());
        LambdaQueryWrapper<SysNotice> queryWrapper = Wrappers.lambdaQuery(SysNotice.class)
                .like(SysNotice::getTitle, param.getTitle())
                .orderByDesc(SysNotice::getCreateTime);
        IPage<SysNotice> pageData = sysNoticeService.page(page, queryWrapper);
        return ResultUtils.success("查询成功", pageData);
    }
}
